package org.scboy.common.dynamic.node.serviceNode;

import org.scboy.common.annotation.ScriptNode;
import org.scboy.common.beans.DynamicServiceResult;
import org.scboy.common.dynamic.node.BaseNode;
import org.scboy.utils.entitys.coobi.Model;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;

@ScriptNode("SERVICE_EXE")
public class ServiceExeNode extends BaseNode {

	private String serviceCode;
	private String appName;
	
	@Override
	public void create(JSONObject object) {
		serviceCode=object.getStr("serviceCode");
		appName=object.getStr("appName");
	}

	@Override
	public Object run() {
		/**
		 * 测试日志
		 */
		if(this.script.isTest()) {
			this.script.appendMsg("----->开始执行："+getNodeName()+" 节点ID："+this.getId());
		}
		
		if(StrUtil.isEmpty(serviceCode)) {
			throw new RuntimeException(getNodeName()+"serviceCode没有值，无法执行。");
		}

		if(StrUtil.isEmpty(appName)) {
			throw new RuntimeException(getNodeName()+"appName没有值，无法执行。");
		}
		
		/**
		 * 流出节点
		 */
		BaseNode runTo = getRunTo("to");
		
		Model params=getSourceData("params", true, Model.class);
		
		//设置请求头，请求类型为json
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);

		//用HttpEntity封装整个请求报文
		HttpEntity<Model> request = new HttpEntity<Model>(params, headers);

		//调用动态服务
		DynamicServiceResult result=this.script.getTemplate().postForObject("http://"+appName+"/dynamic/service/"+serviceCode,request, DynamicServiceResult.class);
		
		this.setData("entity", result.getEntity());

		this.setData("list", result.getList());
		
		/**
		 * 测试日志
		 */
		if(this.script.isTest()) {
			this.script.appendMsg("缓存数据：\r\n"+entityToString(this.getDataAll()));
			this.script.appendMsg("执行下个节点："+runTo.getNodeName()+" 节点ID："+runTo.getId());
		}
		return runTo.run();
	}

}
